package com.yanqu.road.web.controller.usercenter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.dao.impl.admin.AdminCommonDaoImpl;
import com.yanqu.road.entity.admin.AdminResult;
import com.yanqu.road.entity.admin.AdminResult2;
import com.yanqu.road.entity.enums.eServerState;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.utils.http.HttpHelper;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.WebServer;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.*;

@RestController
@RequestMapping("/usercenter/admin")
public class CenterMailAdminFrontController {

    /**
     *  5.1 个人邮件发送
     */
    @ResponseBody
    @RequestMapping(value = "userMail", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String userMail(HttpServletRequest request, @RequestBody String json){

        if(StringUtils.isNullOrEmpty(json)){
            return AdminResult.failMsg("请求参数空").toJsonString();
        }

        JSONObject jsonObject = JSONObject.parseObject(json);

        //邮件奖励
        String annexes = "";
        if(jsonObject.containsKey("annexes")){
            annexes = jsonObject.getString("annexes");
        }

        //玩家
        if(!jsonObject.containsKey("userIds")){
            return AdminResult.failMsg("userIds 为空").toJsonString();
        }

        if(!jsonObject.containsKey("personalId")){
            return AdminResult.failMsg("personalId 为空").toJsonString();
        }

        long personalId = jsonObject.getLongValue("personalId");
        if(personalId <= 0){
            return AdminResult.failMsg("personalId 无效参数").toJsonString();
        }

        Map<Long, List<Long>> serverUserMap = new HashMap<>();
        JSONArray userIds = jsonObject.getJSONArray("userIds");
        for (int i = 0; i < userIds.size(); i++) {
            long uid = userIds.getLongValue(i);
            long serverId = getUserServerId(uid);
            if(!serverUserMap.containsKey(serverId)){
                serverUserMap.put(serverId, new ArrayList<>());
            }
            serverUserMap.get(serverId).add(uid);
        }


        if(!jsonObject.containsKey("contentList")){
            return AdminResult.failMsg("contentList 为空").toJsonString();
        }

        //邮件内容
        JSONArray jsonArray = jsonObject.getJSONArray("contentList");

        int channelId = jsonObject.getIntValue("channelId");
        int type = jsonObject.getIntValue("type");

        if(type == 1){
            if(jsonArray == null){
                jsonArray = new JSONArray();
            }
            List<Integer> goodsList = StringUtils.stringToIntegerList(annexes, "=");
            if(goodsList.size() == 2){
                //从库里拉取宝箱的主语言
                Integer goodsId = goodsList.get(0);
                Map<String, Object> map = new AdminCommonDaoImpl().getPlatformGoods(channelId, goodsId);
                if(!map.isEmpty()){
                    //从库里拉取宝箱的多语言
                    String mailTitle = (String)map.get("mailTitle");
                    String mailContent = (String)map.get("mailContent");
                    Map<Integer, List<Map<String, Object>>> boxLanuage = new AdminCommonDaoImpl().getBroacdeBoxLanuage(Collections.singletonList(goodsId), channelId);
                    List<Map<String, Object>> list = boxLanuage.get(goodsId);
                    Map<String, Map<String, Object>> languageMap = new HashMap<>();
                    if(list != null){
                        //根据多语言key,拼装多语言(标题、内容多语言合并成一个obj)
                        for (Map<String, Object> objectMap : list) {
                            String language = (String)objectMap.get("language");
                            if(!languageMap.containsKey(language)){
                                languageMap.put(language, new HashMap<>());
                            }
                            String key = (String)objectMap.get("key");
                            if(mailTitle.equals(key)){
                                languageMap.get(language).put("title", objectMap.get("content"));
                            }else if(mailContent.equals(key)){
                                languageMap.get(language).put("content", objectMap.get("content"));
                            }
                        }
                    }
                    //数据库捞的多语言，传给游戏服  contentList
                    for (Map.Entry<String, Map<String, Object>> entry : languageMap.entrySet()) {
                        String language = entry.getKey();
                        Map<String, String> obj = new HashMap<>();
                        obj.put("language", language);
                        obj.put("title", (String)entry.getValue().get("title"));
                        obj.put("content", (String)entry.getValue().get("content"));
                        jsonArray.add(obj);
                    }
                }
            }
        }

        int activityId = 0;
        if(jsonObject.containsKey("activityId")){
            String param = jsonObject.getString("activityId");
            if(!StringUtils.isNullOrEmpty(param)){
                activityId = Integer.parseInt(param);
            }
        }

        AdminResult result = AdminResult.defaultInstance();


        List<JSONArray> serverResult = new ArrayList<>();
        if(serverUserMap.size() > 0){
            List<Future> futureList = new ArrayList<>();
            ExecutorService webExecutor = WebServer.getWebExecutor();

            for (Map.Entry<Long, List<Long>> entry : serverUserMap.entrySet()) {
                long sid = entry.getKey();
                ServerInfo serverInfo = ServerListMgr.getServerInfo(sid);
                if(serverInfo == null){
                    result.getData().put(String.valueOf(sid), entry.getValue());
                    continue;
                }

                JSONObject param = new JSONObject();
                param.put("annexes", annexes);
                param.put("personalId", personalId);
                param.put("userIds", StringUtils.listToString(entry.getValue(), ","));
                param.put("contentList", jsonArray);
                param.put("activityId", activityId);

                Future future = webExecutor.submit(new Callable<Boolean>() {
                    @Override
                    public Boolean call() throws Exception {
                        String response = "";
                        try {
                            response = HttpHelper.doPostJson(serverInfo.getWebServerUrl() + "/game/admin/userMail", param.toJSONString(), "UTF-8");
                            AdminResult temp = JSONObject.parseObject(response, AdminResult.class);
                            if(temp.getData().containsKey("-1")){
                                synchronized (serverResult){
                                    result.getData().put(String.valueOf(serverInfo.getServerId()), temp.getData().getJSONArray("-1"));
                                }
                            }
                        } catch (Exception ex) {
                            ServerListMgr.getLogger().error("error, {} {}", response, ex.toString());
                        }
                        return true;
                    }
                });
                futureList.add(future);

            }
            if(!futureList.isEmpty()) {
                for (Future future : futureList) {
                    try {
                        future.get(5, TimeUnit.SECONDS);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    } catch (TimeoutException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        if(result.getData().keySet().size() > 0){
            result.setMsg("部分失败");
            result.setCode(-1);
        }

        return result.toJsonString();
    }



    /**
     *  5.2 群发邮件发送
     */
    @ResponseBody
    @RequestMapping(value = "serverMail", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String serverMail(HttpServletRequest request, @RequestBody JSONObject jsonObject){

        int channelId = jsonObject.getIntValue("channelId");

        //邮件奖励
        String annexes = "";
        if(jsonObject.containsKey("annexes")){
            annexes = jsonObject.getString("annexes");
        }

        //区服
        if(!jsonObject.containsKey("serverIds")){
            return AdminResult.failMsg("serverIds 为空").toJsonString();
        }
        List<Long> serverIdList = new ArrayList<>();
        JSONArray serverIds = jsonObject.getJSONArray("serverIds");
        for (int i = 0; i < serverIds.size(); i++) {
            long longValue = serverIds.getLongValue(i);
            serverIdList.add(longValue);
        }

        if(!jsonObject.containsKey("contentList")){
            return AdminResult.failMsg("contentList 为空").toJsonString();
        }

        int type = jsonObject.getIntValue("type");

        String appId = jsonObject.getString("appId");

        long massId = 0;
        if(jsonObject.containsKey("massId")){
            massId = jsonObject.getLongValue("massId");
        }

        AdminResult2 result = AdminResult2.defaultInstance();

        //邮件内容
        JSONArray jsonArray = jsonObject.getJSONArray("contentList");

        if(type == 1){
            if(jsonArray == null){
                jsonArray = new JSONArray();
            }
            List<Integer> goodsList = StringUtils.stringToIntegerList(annexes, "=");
            if(goodsList.size() == 2){
                //从库里拉取宝箱的主语言
                Integer goodsId = goodsList.get(0);
                Map<String, Object> map = new AdminCommonDaoImpl().getPlatformGoods(channelId, goodsId);
                if(!map.isEmpty()){
                    //从库里拉取宝箱的多语言
                    String mailTitle = (String)map.get("mailTitle");
                    String mailContent = (String)map.get("mailContent");
                    Map<Integer, List<Map<String, Object>>> boxLanuage = new AdminCommonDaoImpl().getBroacdeBoxLanuage(Collections.singletonList(goodsId), channelId);
                    List<Map<String, Object>> list = boxLanuage.get(goodsId);
                    Map<String, Map<String, Object>> languageMap = new HashMap<>();
                    if(list != null){
                        //根据多语言key,拼装多语言(标题、内容多语言合并成一个obj)
                        for (Map<String, Object> objectMap : list) {
                            String language = (String)objectMap.get("language");
                            if(!languageMap.containsKey(language)){
                                languageMap.put(language, new HashMap<>());
                            }
                            String key = (String)objectMap.get("key");
                            if(mailTitle.equals(key)){
                                languageMap.get(language).put("title", objectMap.get("content"));
                            }else if(mailContent.equals(key)){
                                languageMap.get(language).put("content", objectMap.get("content"));
                            }
                        }
                    }
                    //数据库捞的多语言，传给游戏服  contentList
                    for (Map.Entry<String, Map<String, Object>> entry : languageMap.entrySet()) {
                        String language = entry.getKey();
                        Map<String, String> obj = new HashMap<>();
                        obj.put("language", language);
                        obj.put("title", (String)entry.getValue().get("title"));
                        obj.put("content", (String)entry.getValue().get("content"));
                        jsonArray.add(obj);
                    }
                }
            }
        }

        List<Long> serverResult = new ArrayList<>();
        if(serverIdList.size() > 0){
            List<Future> futureList = new ArrayList<>();
            ExecutorService webExecutor = WebServer.getWebExecutor();

            for (Long sid : serverIdList) {
                ServerInfo serverInfo = ServerListMgr.getServerInfo(sid);
                if(serverInfo == null){
                    serverResult.add(sid);
                    continue;
                }

                JSONObject param = new JSONObject();
                param.put("annexes", annexes);
                param.put("appId", appId);
                param.put("contentList", jsonArray);
                param.put("massId", massId);
                param.put("type", type);

                Future future = webExecutor.submit(new Callable<Boolean>() {
                    @Override
                    public Boolean call() throws Exception {
                        String response = "";
                        try {
                            response = HttpHelper.doPostJson(serverInfo.getWebServerUrl() + "/game/admin/serverMail", param.toJSONString(), "UTF-8");
                            AdminResult2 temp = JSONObject.parseObject(response, AdminResult2.class);
                            if(temp.getCode() == -1){
                                synchronized (serverResult){
                                    serverResult.add(sid);
                                }
                            }
                        } catch (Exception ex) {
                            ServerListMgr.getLogger().error("error, {} {}", response, ex.toString());
                        }
                        return true;
                    }
                });
                futureList.add(future);

            }
            if(!futureList.isEmpty()) {
                for (Future future : futureList) {
                    try {
                        future.get(5, TimeUnit.SECONDS);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    } catch (TimeoutException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if(serverResult.size() == serverIdList.size()){
            AdminResult2.failMsg("发送失败");
        }
        return result.toJsonString();

    }

    /**
     *  5.3 个人邮件查看状态和领取状态
     */
    @ResponseBody
    @RequestMapping(value = "viewMailState", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String viewMailState(HttpServletRequest request, @RequestBody JSONObject jsonObject){

        if(!jsonObject.containsKey("personalId")){
            return AdminResult.failMsg("personalId 为空").toJsonString();
        }

        long personalId = jsonObject.getLongValue("personalId");
        if(personalId <= 0){
            return AdminResult.failMsg("personalId 无效参数").toJsonString();
        }

        if(!jsonObject.containsKey("userId")){
            return AdminResult.failMsg("userId 为空").toJsonString();
        }
        long userId = jsonObject.getLongValue("userId");

        long serverId = getUserServerId(userId);
        ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);
        if(serverInfo != null && serverInfo.getState() == eServerState.Normal.getValue()){
            //拉长超时时间
            Map<String, String> response = HttpHelper.httpPostJson(serverInfo.getWebServerUrl() + "/game/admin/viewMailState", jsonObject.toJSONString(), "UTF-8",
                    null, 30 * 1000, 30 * 1000, 30 * 1000);
            String code = response.getOrDefault("code", "0");
            if("200".equals(code)){
                String body = response.get("body");
                AdminResult2 temp = JSONObject.parseObject(body, AdminResult2.class);
                if(temp != null){
                    if(temp.getCode() != -1){

                    }
                }
                return body;
            }
        }

        return AdminResult2.defaultInstance().toJsonString();
    }


    public static long getUserServerId(long userId){
        long userServerId = 0;
        try {
            userServerId = Long.parseLong(String.valueOf(userId).substring(0, 8));
        }catch (Exception e){

        }
        return userServerId;
    }

}
